<?php
namespace addons\food\model;

use app\common\model\Applet as AppletModel;
use app\common\model\AppletTpl;
use app\common\model\Record;
use app\common\model\Template;
use app\common\model\User;
use app\common\model\DivideAccount;
use app\common\model\Setting as SettingModel;
use app\common\model\Apply;
use app\common\model\AppletName;
use app\common\model\Wechat;
use app\common\model\SignLog;
use app\common\model\Address;
use app\common\model\food\Device;
use app\common\model\food\Page;
use app\common\model\food\Shop;
use app\common\model\food\Setting;
use app\common\model\food\RechargePlan;
use app\common\model\food\Coupon;
use app\common\model\food\Help;
use app\common\model\food\Flavor;
use app\common\model\food\Table;
use app\common\model\food\CouponLog;
use app\common\model\food\CouponUser;
use app\common\model\food\Pact;
use app\common\model\food\Comment;
use app\common\model\food\Order;
use app\common\model\food\Spec;
use app\common\model\food\SpecValue;
use addons\upload\model\UploadFile;
use addons\upload\model\UploadGroup;
use think\facade\Db;

/**
 * 小程序模型
 */
class Applet extends AppletModel
{
    /**
     * 创建小程序
     * @param [type] $data     数据
     * @param string $data_type 数据类型 add=用户新增,apply=平台入驻
     */
    public function add(array $data)
    {
    	$pay = 0;//商户支付费用
    	$agent_price = 0;//代理费用
    	if($data['data_type']=='add'){
			$template = Template::where('app_type',$data['app_type'])->find();//获取版本详情
			//判断是否试用
			if($data['year']>0){
				//计算费用
				if($data['shop_mode']==10){
					//单商户
					$pay = $template['buy_single'][$data['year']];
					$agent_price = $template['single_price']*$data['year'];
				}
				if($data['shop_mode']==20){
					//多商户
					$pay = $template['buy_many'][$data['year']-1];
					$agent_price = $template['many_price']*$data['year'];
				}
				$expire_time = strtotime('+'.$data['year'].'year');//计算到期时间
			}else{
				$expire_time = time()+$template['trial_day']*3600*24;//计算到期时间
			}
			$data['expire_time'] = $expire_time;
		}
		// 开启事务
        Db::startTrans();
        try {
			//扣费
			if($data['data_type']=='add' AND $pay>0){
			    $user = User::get($data['user_id']);//获取商户详情
		        $admin_price = $pay;//平台获取费用
				$order_list = [];
				$order_no = order_no();
				array_push($order_list,[
					'user_type' => 20,
					'action' => 40,//扣减
					'order_no' => $order_no,
					'money' => $pay,
					'remark' => '购买小程序模板',
					'user_id' => $data['user_id']
				]);
				//用户扣费
				$money = $user['money']-$pay;//计算扣除后的余额
				$user->money = ['dec',$pay];
				$user->score = ['inc',$pay]; //增加积分
				$user->pay = ['inc',$pay]; //增加消费金额
				$user->save();
				//代理分账
				if($data['agent_id'] > 0){
				    if($pay - $agent_price < 0){
				        $this->error = '销售金额小于代理金额';
				        return false;
				    }
				    $admin_price = $agent_price;//平台获取费用
					//代理分红
					$agent = User::getUser(['user_id' => $data['agent_id']]);
					$agent->money = ['inc',$pay - $agent_price];
					$agent->save();
					array_push($order_list,[
						'user_type' => 30, //代理
						'action' => 50,//分红
						'order_no' => $order_no,
						'money' => $pay - $agent_price,
						'remark' => '销售模板分红',
						'user_id' => $data['agent_id']
					]);						
				}
				//平台收入记录
				if($admin_price > 0){
    				array_push($order_list,[
    					'user_type' => 40, //平台
    					'action' => 50,//分红
    					'order_no' => $order_no,
    					'money' => $admin_price,
    					'remark' => '销售模板'
    				]);
				}
				//添加流水记录
				$model = new Record;
				$model->saveAll($order_list);
			}
			// 添加小程序记录
			$this->save($data);
			// 新增小程序diy配置
			$Page = new Page;
			$Page->insertDefault($this->applet_id,$data);
			// 新增默认门店
			$Shop = new Shop;
			$Shop->insertDefault($this->applet_id,$data);

			Db::commit();
			if($data['data_type']=='add'){
				if($pay>0){
					//账户资金变动提醒
					sand_account_change_msg('购买小程序模板',$pay,$money,$data['user_id']);
				}else{
					//试用申请成功通知
					sand_testing_msg('小程序模板',$expire_time,$data['user_id']);
				}
			}
            return $this->applet_id;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 删除数据
     */
    public function remove($applet_id)
    {
    	$filter['applet_id'] = $applet_id;
		// 开启事务
        Db::startTrans();
        try {
			$this->clear($applet_id);
			DivideAccount::where($filter)->delete();
			Setting::where($filter)->delete();
			SettingModel::where($filter)->delete();
			Page::where($filter)->delete();
			Spec::where($filter)->delete();
			SpecValue::where($filter)->delete();
			RechargePlan::where($filter)->delete();
			Coupon::where($filter)->delete();
			AppletTpl::where($filter)->delete();
			Help::where($filter)->delete();
			Apply::where($filter)->delete();
			AppletName::where($filter)->delete();
			Device::where($filter)->delete();
			Flavor::where($filter)->delete();//点餐专属
			Table::where($filter)->delete();//点餐专属
			$model = new Wechat;
        	$model->clear($applet_id); 
			//清除门店记录
            $shopId = (new Shop)->where($filter)->column('shop_id');
            for($n=0;$n<sizeof($shopId);$n++){
                (new Shop)->remove($shopId[$n],true);
            }
            if(get_addons_info('upload')){
                UploadFile::where($filter)->delete();
			    UploadGroup::where($filter)->delete();
            }
			$this->where($filter)->delete();
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}

	/**
     * 清除数据
     */
    public function clear($applet_id)
    {
    	$filter['applet_id'] = $applet_id;
		// 开启事务
        Db::startTrans();
        try {
        	SignLog::where($filter)->delete();
        	CouponLog::where($filter)->delete();
        	CouponUser::where($filter)->delete();
			Record::where($filter)->delete();
			Pact::where($filter)->delete();
			Address::where($filter)->delete();
			User::where($filter)->delete();  
			Comment::where($filter)->delete();
			//清除订单记录
            $orderId = (new Order)->where($filter)->column('order_id');
            for($n=0;$n<sizeof($orderId);$n++){
                (new Order)->remove($orderId[$n]);
            }     	
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}
}
